/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * MpmProjectAppointmentController
 * 项目任命
 * <p>
 * 修改纪录
 * 2020-12-28 版本：1.0 lanjianwei 创建。
 *
 * @version 版本：1.0
 * @author 作者：lanjianwei
 * 创建日期：2020-12-28
 */

package com.topscomm.mpm.controller;

import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.ICboAttachmentService;
import com.topscomm.mpm.controller.auto.MpmProjectAppointmentControllerAuto;
import com.topscomm.mpm.pojo.MpmProjectAppointmentEntity;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.mpm.service.IMpmProjectService;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.ParameterCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: lanjianwei
 * @date: 2020-12-28
 * @description:项目任命Controller
 * @modify:
 */
@RestController
@RequestMapping("mpm/projectAppointment")
public class MpmProjectAppointmentController extends MpmProjectAppointmentControllerAuto implements IMpmProjectAppointmentController {
    private Logger logger = LoggerFactory.getLogger(MpmProjectAppointmentController.class);
    @Autowired
    private IMpmProjectService mpmProjectService;
    @Autowired
    private ICboAttachmentService cboAttachmentService;

    /**
     * @author: lanjianwei
     * @date: 2020-12-28
     * @param paraMap
     * @return
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled=1 ");
        if (paraMap.containsKey("qry_projectcode")) {
            String value = paraMap.get("qry_projectcode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and  projectcode = '{0}' ", value);
        }
        if (paraMap.containsKey("qry_projectname")) {
            String value = paraMap.get("qry_projectname").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and  projectname like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_appointmenttitle")) {
            String value = paraMap.get("qry_appointmenttitle").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and  appointmenttitle like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_appointmentdescription")) {
            String value = paraMap.get("qry_appointmentdescription").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and  appointmentdescription like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_user")) {
            String value = paraMap.get("qry_user").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (applyusercode = '{0}' or applyusername like '%{0}%') ", value);
        }
        if (paraMap.containsKey("qry_singer")) {
            String value = paraMap.get("qry_singer").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (signercode = '{0}' or signername like '%{0}%') ", value);
        }
        if (paraMap.containsKey("qry_state")) {
            String value = paraMap.get("qry_state").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and state={0}", value);
        }
        if (paraMap.containsKey("qry_docno")) {
            String value = paraMap.get("qry_docno").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and docno like '%{0}%'", value);
        }
        if (paraMap.containsKey("qry_begindocdate")) {
            String value = paraMap.get("qry_begindocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        if (paraMap.containsKey("qry_deptname")) {
            String value = paraMap.get("qry_deptname").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
        }
        if (paraMap.containsKey("qry_deptcode")) {
            String value = paraMap.get("qry_deptcode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and deptcode like '{0}%'", value);
        }
        if (paraMap.containsKey("qry_where")) {
            String value = paraMap.get("qry_where").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and {0}", value);
        }
/*		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", this.getUserBean());
			if (StringUtil.isEmpty(dataPession))// 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据
			{
				String deptcodes_header = ConvertUtil.convertToString(this.getUserBean().getUser().getValue("deptcodes_header"));
				if (StringUtil.isEmpty(deptcodes_header))
					sql.appendSingle(" and (usercode = '{0}' or deptcode ='{1}' or deptcode = '{2}' )", this.getUserBean().getUser().getCode(), this.getUserBean().getDept().getCode(), this
							.getUserBean().getWorkDept().getCode());
				else
					sql.appendSingle(" and (deptcode in ({0})  or usercode = '{1}' or deptcode ='{2}' or deptcode = '{3}' )", deptcodes_header, this.getUserBean().getUser().getCode(), this
							.getUserBean().getDept().getCode(), this.getUserBean().getWorkDept().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}*/
        return sql.toString();
    }

    /**
     * @author: lanjianwei
     * @date: 2020-12-28
     * @param paraMap
     * @return
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }

    /**
     *
     * @description: 提交审批前
     * @param dataMap
     * @param paraMap
     * @throws Exception
     * @author: lanjianwei
     * @date: 2020-12-28
     * @modify:
     */
    @Override
    protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
        super.beforeSubmit(dataMap, paraMap);
        StringBufferProxy mailtitle = new StringBufferProxy();
        mailtitle.appendSingle("{0}{1}于{2}提交项目任命申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
        dataMap.put("maintitle", mailtitle.toString());
    }


    @PutMapping({"/approval"})
    @Override
    public ResponseResult<Object> approval(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            String approvalOpinion = paraMap.get("approvalopinion").toString();
            String approvalType = paraMap.get("approvaltype").toString();
            String nodeInsId = paraMap.get("nodeinsid").toString();
            String backNodeId = ConvertUtil.convertToString(paraMap.get("backnodeid"));
            long nextUserId = 0L;
            if (paraMap.containsKey("nextuserid") && !StringUtil.isEmpty(paraMap.get("nextuserid").toString())) {
                nextUserId = Long.parseLong(paraMap.get("nextuserid").toString());
            }
            if ("".equals(approvalOpinion) && "1".equals(approvalType)) {
                approvalOpinion = "同意";
            }
            this.service.executeApprove(nodeInsId, new Date(), approvalOpinion, approvalType, backNodeId, this.getUserBean(), nextUserId);
            return ResponseResult.ok("操作成功");
        } catch (Exception var8) {
            return this.handleControllerException(var8);
        }
    }


    @PostMapping({"/generateAppointment"})
    public ResponseResult<Object> generateAppointment(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            this.service.generateAppointment(paraMap);
            return ResponseResult.ok("操作成功");
        } catch (Exception var8) {
            return this.handleControllerException(var8);
        }
    }

    @Override
    protected void afterLoad(Map<String, Object> paraMap) {
        String projectCode = ConvertUtil.convertToString(paraMap.get("projectcode"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" projectcode = '{0}' ", projectCode);
        List<MpmProjectEntity> mpmProjectInfoList = mpmProjectService.queryByWhere(sql.toString());
        if (CollectionUtils.isEmpty(mpmProjectInfoList)) {
            return;
        }
        MpmProjectEntity mpmProjectInfo = mpmProjectInfoList.get(0);
        paraMap.put("projectname", mpmProjectInfo.getProjectname());
        paraMap.put("projectcreateon", mpmProjectInfo.getCreateon());
    }

    @PostMapping(value = "/download")
    public void download(@RequestBody Map<String, Object> paraMap, HttpServletRequest request, HttpServletResponse response) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Map<String, Object> resultMap = this.service.executeDownload(paraMap);
            // 设置文件名字(给要下载文件重命名);
            String fileName = ConvertUtil.convertToString(resultMap.get("attFileName"));
            response.setContentType("application/octet-stream");
            // response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            InputStream inStream = BaseUtil.convertByteToStream((byte[]) resultMap.get("attInputStream"));
            OutputStream outStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while ((len = inStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            inStream.close();
        } catch (Exception e) {
            throw new BusinessException(e);
        }
    }

    @PostMapping({"/sendmail"})
    public ResponseResult<Object> sendmail(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            this.service.sendMessage(ConvertUtil.convertToString(paraMap.get("appointid")));
            return ResponseResult.ok("操作成功");
        } catch (Exception var8) {
            return this.handleControllerException(var8);
        }
    }

    @GetMapping({"/checkappointcount"})
    public ResponseResult<Object> checkappointcount(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            StringBufferProxy sql = new StringBufferProxy();
            String projectCode = ConvertUtil.convertToString(paraMap.get("projectcode"));
            boolean isAdd = ConvertUtil.convertToBoolean(paraMap.get("isAdd"));
            String id = ConvertUtil.convertToString(paraMap.get("id"));
            Map<String, Object> result = new HashMap<>();
            // 若是新增任命则判断是否有已审批任命书
            if (isAdd) {
                sql.appendSingle("projectcode = '{0}' and enabled = '1' and state = '9'", projectCode);
                result.put("isFirstAppoint", this.service.getCount(sql.toString()) == 0);
            } else {
                // 查询打开的任命书
                MpmProjectAppointmentEntity mpmProjectAppointmentEntity = this.service.queryById(id);
                // 若无变更信息则证明为一次任命
                if (StringUtil.isEmpty(mpmProjectAppointmentEntity.getChangecontent())) {
                    result.put("isFirstAppoint", true);
                } else {
                    result.put("isFirstAppoint", false);
                }
            }
            return ResponseResult.ok(result);
        } catch (Exception var8) {
            return this.handleControllerException(var8);
        }
    }

    /**
    * @Description:    获取默认签发人
    * @Author:         mengmeng
    * @Date:           2021/8/28 14:03
    * @Version:        1.0
    */
    @GetMapping({"/getDefaultSigner"})
    public ResponseResult<Object> getDefaultSigner(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            String projectCode = ConvertUtil.convertToString(paraMap.get("qry_projectcode"));
            List<MpmProjectEntity> mpmProjectDoList = mpmProjectService.queryByWhere(" projectcode = '" + projectCode + "'");
            MpmProjectEntity mpmProjectDo = mpmProjectDoList.get(0);
            String projectLevel = mpmProjectDo.getProjectlevel();
            Map<String, Object> result = new HashMap<>();
            // A、B级项目默认林总审批
            if ("1".equals(projectLevel) || "0".equals(projectLevel)) {
                String mpmDefaultSigner = ParameterCache.getValue("MpmDefaultSigner", "0070,林道良");
                if (!StringUtil.isEmpty(mpmDefaultSigner)) {
                    String[] split = mpmDefaultSigner.split(",");
                    result.put("signercode", StringUtil.isEmpty(split[0]) ? "" : split[0]);
                    result.put("signername", StringUtil.isEmpty(split[1]) ? "" : split[1]);
                }
            }
            else {
                // C、D级项目默认为省总
                String deptCode = mpmProjectDo.getDeptcode();
                String firstDeptCode = "";
                String sql = "";
                if (deptCode.contains("_")) {
                    int endLength = deptCode.indexOf("_") + 5;
                    firstDeptCode = endLength <= deptCode.length() ? deptCode.substring(0, endLength) : deptCode;
                    sql = "', 0, " + endLength + ") = b.deptcode";
                } else {
                    firstDeptCode = deptCode.substring(0, 4);
                    sql =  "', 0, 4) = b.deptcode";
                }
                List<Map<String, Object>> maps = this.service.selectExecute(" select a.code, a.name from cbouser a inner join misdeptheader b on b.usercode = a.code where b.category = 'CEO' and  substr('" + firstDeptCode + sql);
                if (!CollectionUtils.isEmpty(maps)) {
                    Map<String, Object> map = maps.get(0);
                    result.put("signercode", map.get("code"));
                    result.put("signername", map.get("name"));
                }
            }
            return ResponseResult.ok(result);
        } catch (Exception var8) {
            return this.handleControllerException(var8);
        }
    }

    @PostMapping(value = "/upload")
    public ResponseResult<Object> upload(@RequestParam("file") MultipartFile file, @RequestParam(required = false) Map<String, Object> paraMap) {
        File attachFile = null;
        try {

            if (file == null || file.getSize() <= 0)
                return ResponseResult.error("找不到合法的文件");
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            attachFile = multipartFileToFile(file);
            // 先删除之前的附件
            String sourceId = ConvertUtil.convertToString(paraMap.get("sourceId"));
            cboAttachmentService.deleteByWhere(" sourcetype = 'MpmProjectAppointmentGenerate' and sourceid = " + sourceId);
            Map<String, Object> map = this.cboAttachmentService.executeUpload(paraMap, attachFile);

            return ResponseResult.ok(map);
        } catch (Exception e) {
            return ResponseResult.error(e.getMessage());
        } finally {
            if (attachFile != null) {
                Boolean boo = attachFile.delete();
                if (!boo) {
                    logger.info("文件删除失败，请联系管理员！");
                }
            }
        }
    }

    /**
     * @author zhanglongfei
     * @date 2020年2月12日
     * @description upload获取到的文件转换
     * @param file
     * @return
     * @throws Exception
     */
    private File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file == null || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    // 获取流文件
    private void inputStreamToFile(InputStream ins, File file) {
        try (OutputStream os = new FileOutputStream(file)) {
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @author: houyuhang
     * @date: 2022-07-15
     * @param: paraMap
     * @description: 重写datacodelist
     * @modify:
     **/
    @Override
    @GetMapping(value = "/dataCodeList")
    public ResponseResult<Object> dataCodeList(@RequestParam(required = false) Map<String, Object> paraMap) {
        ResponseResult<Object> res = super.dataCodeList(paraMap);
        Map<String, Object> codeMap = (Map<String, Object>) res.getResult();
        List<Map<String, Object>> businessRoleDutyList = datacodeCache.getCodeListMap("MpmBusinessRoleDuty", "", "sortcode");
        codeMap.put("businessRoleDutyList", businessRoleDutyList);
        List<Map<String, Object>> bidGuideDutyList = datacodeCache.getCodeListMap("MpmBidGuideDuty", "", "sortcode");
        codeMap.put("bidGuideDutyList", bidGuideDutyList);
        List<Map<String, Object>> bidBookDutyList = datacodeCache.getCodeListMap("MpmBidBookDuty", "", "sortcode");
        codeMap.put("bidBookDutyList", bidBookDutyList);
        return ResponseResult.ok(codeMap);
    }
}

